#!/bin/bash
# get executable name
full=$(ls *.cc)
filename=$(basename "$full")
extension="${filename##*.}"
exe="${filename%.*}"
# logs
outputdir="output"
logdir=$outputdir"/log"
bakdir=$outputdir"/bak"
runNo=$(printf "%.5d" "$1")
rootfile="output/run"$runNo".root"
runlog=$outputdir"/run.log"
#echo $rootfile
str=""

./build.sh #make sure the executable is up to date 
date1=$(date +"%s")
echo $(date) "- Run "$runNo" started: "$0 $1 $2 $3 >>$runlog
if [ $# -gt 3 ]
then
	echo "Comments: "$4>>$runlog
fi

if [ $# -gt 1 ] 				#check if there are more than 1 parameter
then 
	NoOfJobs=$2
	echo "Number of parallel subruns: " $NoOfJobs
else										#default no. of subruns: 4
	echo "Run with default number of parallel subruns: 4"
	NoOfJobs=4
fi

if [ $# -gt 2 ] 				#check if there are more than 2 parameter
then 
	batch=$3
else										#default batch macro
	batch="macro/batch.mac"
fi
echo "Batch macro: " $batch

if [ -d $logdir ]
then
	echo "Log directory existed, skip creating!"
else
	echo "Create log directory: "$logdir
	mkdir $logdir
fi

if [ -d $bakdir ]
then
	echo "Back up directory existed, skip creating!"
else
	echo "Create back up directory: "$bakdir
	mkdir $bakdir
fi

if [ -f $rootfile ] 		#check if the output file is existed
then
	echo "File existed, run aborted!!!"
else               			#if not, then run 
	echo "Run "$1" started..."
	for ((i=1;i<=$NoOfJobs;i++))
	do
		subrun="output/run"$1"-"$i".root"
		log=$logdir"/log"$1"-"$i
		err=$logdir"/err"$1"-"$i
		$exe $batch $subrun 1>$log 2>$err  &
		sleep 2
		str=$str" "$subrun
	done
	
	#Progress bar
	#sleep 3
	#cd progressbar
	#python showprog.py $1 $2
	#cd ..

	wait									# wait until all subruns stop

	if [ $NoOfJobs -gt 1 ]
	then 
		hadd $rootfile $str		# merge subrun outputs to 1 file 
		rm $str 							# clean up
	else
		mv $str $rootfile
	fi
	# Progress
	#nevt= tail -n1 $logdir"/log"$1"-1"
	#sleep 1
	#echo $nevt

	# Done
	echo "Done!"
fi

date2=$(date +"%s")
diff=$(($date2-$date1))
runtime=$(date -u -d @"$diff" +'%-Mm %-Ss')
echo $(date) "- Run "$runNo" finished! Run time: "$runtime>>$runlog
echo "">>$runlog
